
/*
 * File:   kompartir.c
 * Author: Subhabrata
 *
 * Created on August 12, 2010, 1:15 AM
 */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netdb.h>
#include<fcntl.h>
#include<termios.h>
#include<unistd.h>
#include<errno.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
/* Global Variables*/
int socketFD;
char *serverIP, *portNo;


/* Function Protypes */


/**
 *      -------Main Function-----
 *      @author    Subhabrata
 *
 **/



    

/**
 *      @author         Subhabrata
 *      @param  *msg     print the msg as prefix followed by a colon to the standard error
 **/
void error(char *msg)
{
    perror(msg);
    
    shutdown(socketFD, SHUT_RDWR);
    exit(0);
}

/**
 *      @author         Subhabrata
 *      @param  *port   port  the portno of the server socket
 **/


/**
 *      @author         Subhabrata
 *      @param  portno  portno of the server
 **/
int main(int argc, char** argv)
{

    serverIP=argv[1];
    portNo=argv[2];

    char *buffer,filepath[256];
    int  sBytes, rBytes, file, sSumBytes;
    struct sockaddr_in clientService;
    socketFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (-1 == socketFD)
    {
        perror("cannot create socket");
        exit(EXIT_FAILURE);
    }
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr(serverIP);
    clientService.sin_port = atoi(portNo);
    if (-1 == connect(socketFD, (struct sockaddr *) &clientService, sizeof (clientService)))
    {
        error("connect failed");
        close(socketFD);
        exit(EXIT_FAILURE);
    }
    printf("Enter the file path :");
    gets(filepath);
    file = open(filepath, O_RDONLY);

    if (file == -1)
    {
        printf("ERROR");
    }
    do
    {
        rBytes = read(file, buffer, 10); // here you read a max of 64 bytes
        if (rBytes <= 0) break; // if 0 or -1 either error or end of file
        sSumBytes = 0;
        do
        {
            sBytes = send(socketFD, &buffer[sSumBytes], rBytes - sSumBytes, 0);
            if (sBytes <= 0)
            {
                perror("send");
                break; // you w1anna leave the loop if send failed
            }
            sSumBytes += sBytes;
        }
        while (sSumBytes < rBytes); // repeat until all is sent
    }
    while (sSumBytes == rBytes); // leave if send failed to deliver all
    return 0;
}

